package com.bigfreakindeals.Protocols.SoapHandlers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.sax.*;
import android.util.Log;
import android.util.Xml;

import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Models.ActiveDeal;
import com.bigfreakindeals.Models.Company;
import com.bigfreakindeals.Models.UniversityDeals;

public class GetTodaysDealHandler  {

	// names of the XML tags
	static final String  PARENT = "response";
	   
	static final String  STATUS = "status";
    static final  String DEALS = "deals"; //true ar false
    
    static final  String ITEM = "item";
    static final  String ID = "id";
    static final  String NAME = "name";
    static final  String IS_SIDE_DEAL = "is_side_deal";
    static final  String START_DATE = "start_date";
    static final  String END_DATE="end_date";
    
    static final  String SMALL_IMG_URL = "small_image_url";
    static final  String MED_IMG_URL = "medium_image_url";
    static final  String LARGE_IMG_URL = "large_image_url";
    
    static final  String ORIGINAL_PRICE = "original_price";
    static final  String DISCOUNT_PRICE = "discounted_price";
    static final  String DISCOUNT_PERCENTAGE = "discount_percentage";
    static final  String DISCOUNT_AMOUNT = "discount_amount";
    static final  String SAVINGS = "savings";
    static final  String DEAL_USER_COUNT = "deal_user_count";
    static final  String FINEURL = "fineurl";
    static final  String HIGHLIGHT = "coupon_highlights";
    static final  String DESCRIPTION = "description";
    
    static final String REVIEW = "review";
    static final String COMPANY = "company";
    static final String COMPANY_ID = "company_id";
    static final String COMPANY_NAME = "company_name";
    static final String COMPANY_SLUG = "company_slug";
    static final String COMPANY_ADD1 = "company_address1";
    static final String COMPANY_ADD2 = "company_address2";
    static final String COMPANY_PHONE = "company_phone";
    static final String COMPANY_ZIP = "company_zip";
    static final String COMPANY_CITYNAME = "company_city_name";
    static final String COMPANY_STATENAME = "company_state_name";
    static final String COMPANY_LAT = "company_latitude";
    static final String COMPANY_LONG = "company_longitude";
    static final String COMPANY_URL = "company_url";
    static final String COMPANY_BRANCH = "company_branch_offices";
    
    static final String URL_QUICKEMAILFRIEND = "quick_email_friend_url";
    static final String URL_TWITTERSHARE = "twitter_share_url";
    static final String URL_TWITTERSHARE_TEXT = "twitter_share_text";
    static final String MIN_QUANTITY = "buy_min_quantity_per_user";
    static final String URL_FACEBOOKSHARE = "facebook_url";
  
    
    
    static final String FACEBOOK_URL = "facebook_url";
    static final String TWITTER_URL = "twitter_url";
    
    final byte dealType_HIGHLIGHTS = 1;
    final byte dealType_SIDE = 3;
    final byte dealType_FEATURED = 2;
    
    static final  String ERROR = "error";
   boolean isRefresh = true;
    String feedUrl;
    
    ActiveDeal activeDeal = new ActiveDeal();
    private static final String SOAP_ACTION = "http://unimiser.com/HelloWorld";
    private static final String METHOD_NAME = "bigfreakindeals";
    private static final String NAMESPACE = "http://unimiser.com/";
	
    public GetTodaysDealHandler(String feedUrl, boolean isRefresh) {
    	this.feedUrl = feedUrl;
    	this.isRefresh = isRefresh;
    	
    	System.out.println("getTodaysString");
    	
    	parse();
    	
    	
    }

    
    
    public void parse() {

    	//update UniversityProfile
		ArrayList<ActiveDeal> sortedDeals = new ArrayList<ActiveDeal>();
		
     try {
    	 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    	 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    	 envelope.setOutputSoapObject(request);
    	 HttpTransportSE androidHttpTransport = new HttpTransportSE(feedUrl);

         androidHttpTransport.call(SOAP_ACTION, envelope);
         
      	SoapObject response = (SoapObject)envelope.getResponse();
      
    	 String status  = response.getProperty(STATUS).toString();
    	
    	  if (status !=null && status.length() >0){
			if (status.contentEquals("false")){
				//error on active deals
				//get error message
				
				String error  = response.getProperty(ERROR).toString();
				activeDeal.setDealStatus(false);
							
				if (error !=null && error.length() >0)
					activeDeal.setErrorMessage(error);
				
				ApplicationEx.getInstance().controller.callNodealsPage(error);
				return;
			
			}else {//status = true; active deals exist
				
				Vector dealset = (Vector)response.getProperty("deals");
				System.out.println(response);
				ArrayList<ActiveDeal> dealListSide = new ArrayList<ActiveDeal>();
				ArrayList<ActiveDeal> dealListFeatured = new ArrayList<ActiveDeal>();
				ArrayList<ActiveDeal> dealListhighlights = new ArrayList<ActiveDeal>();
				
				
				for (int count = 0;count <= dealset.size() -1; count++){
					System.out.println(count+" "+dealset.size());
					SoapObject deals = (SoapObject)dealset.get(count);
					ActiveDeal dealItem = new ActiveDeal();
					
					String id = deals.getProperty(ID).toString();
					if (id != null && id.length() > 0)
						dealItem.setDealID(id);

					if (deals.getProperty(NAME) != null)
						dealItem.setDealName(deals.getProperty(NAME).toString());

					if (deals.getProperty(IS_SIDE_DEAL) != null)
						dealItem.setDealType(Integer.parseInt(deals.getProperty(IS_SIDE_DEAL).toString()));

					if (deals.getProperty(START_DATE) != null)
						dealItem.setStartDate(deals.getProperty(START_DATE).toString());
					else
						break;
					System.out.println("gettodaysdeal handler");
					if (deals.getProperty(END_DATE) != null){
						System.out.println("END_DATE");
						
						dealItem.setEndDate(deals.getProperty(END_DATE).toString());
					}else
						break;

					if (deals.getProperty(SMALL_IMG_URL) != null)
						dealItem.setSmallImgUrl(deals.getProperty(SMALL_IMG_URL).toString());

					if (deals.getProperty(MED_IMG_URL) != null)
						dealItem.setMediumImgUrl(deals.getProperty(MED_IMG_URL).toString());

					if (deals.getProperty(LARGE_IMG_URL) != null)
						dealItem.setLargeImgUrl(deals.getProperty(LARGE_IMG_URL).toString());

					if (deals.getProperty(ORIGINAL_PRICE) != null)
						dealItem.setOriginalPrice(deals.getProperty(ORIGINAL_PRICE).toString());

					if (deals.getProperty(DISCOUNT_PRICE) != null)
						dealItem.setDiscountPrice(deals.getProperty(DISCOUNT_PRICE).toString());

					if (deals.getProperty(DISCOUNT_PERCENTAGE) != null)
						dealItem.setDiscountPercent(deals.getProperty(DISCOUNT_PERCENTAGE).toString());

					if (deals.getProperty(DISCOUNT_AMOUNT) != null)
						dealItem.setDiscountAmount(deals.getProperty(DISCOUNT_AMOUNT).toString());

					if (deals.getProperty(SAVINGS) != null)
						dealItem.setSavings(deals.getProperty(SAVINGS).toString());

					
					if (deals.getProperty(DEAL_USER_COUNT) != null)
						dealItem.setDealuserCount(deals.getProperty(DEAL_USER_COUNT).toString());

					if (deals.getProperty(FINEURL) != null){
						dealItem.setFinePrints(deals.getProperty(FINEURL).toString());

					//	System.out.println(dealItem.getFinePrints());
					}
					if (deals.getProperty(HIGHLIGHT) != null){
						dealItem.setHighLights(deals.getProperty(HIGHLIGHT).toString());
					//	System.out.println(dealItem.getHighLightsString());
					}
					if (deals.getProperty(DESCRIPTION) != null ){
						dealItem.setDescription(deals.getProperty(DESCRIPTION).toString());
					//	System.out.println(dealItem.getDescription());
					}
					
					if (deals.getProperty(URL_QUICKEMAILFRIEND) != null){
						
						dealItem.setQuick_email_friend_url(deals.getProperty(URL_QUICKEMAILFRIEND).toString());
						dealItem.setFacebookshare_url(deals.getProperty(URL_QUICKEMAILFRIEND).toString());
				}
					
					if (deals.getProperty(URL_TWITTERSHARE) != null)
						dealItem.setTwitter_share_url(deals.getProperty(URL_TWITTERSHARE).toString());

					if (deals.getProperty(URL_TWITTERSHARE_TEXT) != null)
						dealItem.setTwitter_share_text(deals.getProperty(URL_TWITTERSHARE_TEXT).toString());

					if (deals.getProperty(MIN_QUANTITY) != null)
						dealItem.setMin_quantity(deals.getProperty(MIN_QUANTITY).toString());

					SoapObject itemCompany = (SoapObject) deals.getProperty(COMPANY);

					if (itemCompany != null) {
						Company company = new Company();

						if (itemCompany.getProperty(COMPANY_ADD1) != null)
							company.setCompanyAddress1(itemCompany.getProperty(COMPANY_ADD1).toString());

						if (itemCompany.getProperty(COMPANY_ADD2) != null)
							company.setCompanyAddress2(itemCompany.getProperty(COMPANY_ADD2).toString());

						if (itemCompany.getProperty(COMPANY_ID) != null)
							company.setCompanyID(itemCompany.getProperty(COMPANY_ID).toString());

						if (itemCompany.getProperty(COMPANY_STATENAME) !=null){
							company.setStatename(itemCompany.getProperty(COMPANY_STATENAME).toString());
						}
					
						
/*						if (itemCompany.getProperty(COMPANY_BRANCH) != null)
							company.setBranchOffice(itemCompany.getProperty(COMPANY_BRANCH).toString());
*/
						if (itemCompany.getProperty(COMPANY_CITYNAME) != null)
							company.setCityname(itemCompany.getProperty(COMPANY_CITYNAME).toString());
				
						if (itemCompany.getProperty(COMPANY_LAT) != null)
							company.setLatitude(itemCompany.getProperty(COMPANY_LAT).toString());

						if (itemCompany.getProperty(COMPANY_LONG) != null)
							company.setLongitude(itemCompany.getProperty(COMPANY_LONG).toString());

						if (itemCompany.getProperty(COMPANY_NAME) != null)
							company.setCompanyname(itemCompany.getProperty(COMPANY_NAME).toString());

						if (itemCompany.getProperty(COMPANY_PHONE) != null)
							company.setPhoneNumber(itemCompany.getProperty(COMPANY_PHONE).toString());
						
						if (itemCompany.getProperty(COMPANY_SLUG) != null)
							company.setCompanyslug(itemCompany.getProperty(COMPANY_SLUG).toString());
						
						if (itemCompany.getProperty(COMPANY_URL) != null)
							company.setWebSite(itemCompany.getProperty(COMPANY_URL).toString());

						if (itemCompany.getProperty(COMPANY_ZIP) != null)
							company.setZip(itemCompany.getProperty(COMPANY_ZIP).toString());

						// add company model to the deal item
						dealItem.setCompany(company);

					}//end if
					
					if (dealItem.getDealType() == dealType_HIGHLIGHTS){
						dealListhighlights.add(dealItem);
					}else if (dealItem.getDealType() == dealType_FEATURED){
						dealListFeatured.add(dealItem);				
					}else 
						dealListSide.add(dealItem);
				}//end for
				
				//sort the deals
				//First is the Highlight deals ordered by newest to oldest
				//Followed by featured ordered again by newest to oldest
				//Followed by side-deals ordered again by newest to oldest
				

				if (dealListhighlights!=null && dealListhighlights.size() > 0){
					Collections.sort(dealListhighlights);	
					sortedDeals.addAll(dealListhighlights);
				}
				
				
				if (dealListFeatured!=null && dealListFeatured.size() > 0){
					Collections.sort(dealListFeatured);	
					sortedDeals.addAll(dealListFeatured);
				}
				
				if (dealListSide!=null && dealListSide.size() > 0){
					Collections.sort(dealListSide);	
					sortedDeals.addAll(dealListSide);
				}
			
				for (int i = 0; i<sortedDeals.size();i++){
					System.out.println(i+" "+((ActiveDeal)sortedDeals.get(i)).getDealName()+" "+((ActiveDeal)sortedDeals.get(i)).getStartDateString());
				}
			
			}
			
		}
			
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
	
			Intent intent = new Intent(Constant.EVENTS_HTTPCONNECTION_ERROR); 
			intent.putExtra(Constant.EVENTS_HTTPCONNECTION_MESSAGE, Constant.HTTPCONNECTION_ERROR_MESSAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);
			// TODO Auto-generated catch block
	
		} catch (Exception e1) {
			
			Intent intent = new Intent(Constant.EVENTS_HTTPCONNECTION_ERROR); 
			intent.putExtra(Constant.EVENTS_HTTPCONNECTION_MESSAGE, Constant.HTTPCONNECTION_ERROR_MESSAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//update myProfile deals
		
		ApplicationEx.getInstance().myProfile.getlastSelectedSchool().setDeals(sortedDeals);
		
		if (ApplicationEx.getInstance().progressDialog != null)
			ApplicationEx.getInstance().progressDialog.dismiss();
		
		System.out.println("GETTODAYSDEAL@ISREFRESH"+isRefresh);
		if (isRefresh){
			ApplicationEx.getInstance().controller.getMainTabActivity();
		}
		
	}

}

